const { screen, ipcMain } = require("electron");

/**
 * 窗口移动
 * @param win
 */
function windowMove(win) {

    let winStartPosition = {x: 0, y: 0};
    let mouseStartPosition = {x: 0, y: 0};
    let movingInterval = null;

    /**
     * 窗口移动事件
     */
    ipcMain.on("window-move-open", (events, canMoving) => {
        if (canMoving) {
            // 读取原位置
            const winPosition = win.getPosition();
            winStartPosition = { x: winPosition[0], y: winPosition[1] };
            mouseStartPosition = screen.getCursorScreenPoint();
            // 清除
            if (movingInterval) {
                clearInterval(movingInterval);
            }
            // 新开
            movingInterval = setInterval(() => {
                // 实时更新位置
                const cursorPosition = screen.getCursorScreenPoint();
                const x = winStartPosition.x + cursorPosition.x - mouseStartPosition.x;
                const y = winStartPosition.y + cursorPosition.y - mouseStartPosition.y;

                let cursor = screen.getCursorScreenPoint();
                let curScreen = screen.getDisplayNearestPoint({x: cursor.x, y: cursor.y});
                let { width, height } = curScreen.workAreaSize;
                // let scaleFactor = curScreen.scaleFactor;
                if(width > 1900){
                    width = 1440;
                    height = 900;
                } else {
                    width = 1024;
                    height = 640;
                }

                win.setBounds({
                    width: width ,
                    height: height,
                    x: x,
                    y: y
                });
            }, 20);
        } else {
            if(movingInterval){
                clearInterval(movingInterval);
                movingInterval = null;
            }
        }
    });

}
module.exports = windowMove;
